package com.fulin.leetcode;

import java.util.Locale;

/**
 * 验证回文串
 *
 * @Author fulin
 * @Date 2022/9/21 11:45
 **/
public class Num125_验证回文串 {

    /**
     * 优雅的解法,双指针实现O(1)空间复杂度算法
     * @param s
     * @return
     */
    public boolean isPalindrome1(String s){
        int L = 0,R = s.length() - 1;
        while(L < R){
            while(L < R && !Character.isLetterOrDigit(s.charAt(L))){
                L++;
            }
            while(L < R && !Character.isLetterOrDigit(s.charAt(R))){
                R--;
            }
            if(L < R){
                if(Character.toLowerCase(s.charAt(L)) != Character.toLowerCase(s.charAt(R))){
                    return false;
                }
                L++;
                R--;
            }
        }
        return true;
    }

    /**
     * 正常解法
     * @param s
     * @return
     */
    public boolean isPalindrome(String s) {
        s = s.toLowerCase();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if(isOk(s.charAt(i))){
                sb.append(s.charAt(i));
            }
        }
        int j = 0,k = sb.length() - 1;
        while(j <= k){
            if(sb.charAt(j++) != sb.charAt(k--)){
                return false;
            }
        }
        return true;
    }

    private boolean isOk(char ch){
        return (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z');
    }
}
